<script setup>
import { ref } from 'vue'
import { showSuccessToast } from 'vant';
import { useRouter } from 'vue-router';

const router = useRouter()
const name = ref('')
const phone = ref('')
const imageValue = ref([])
const imageUrl = ref('')

const onSubmit = () => {
  saveEnrollInfo()
}
const afterRead = (file) => {
  // 此时将文件上传至服务器
  uploadImage()
};
// 上传图片到后端
const uploadImage = () => {
  const formData = new FormData()
  formData.append('files', imageValue.value[0].file)
  fetch('/api1/upload/picture',{
    method: "POST",
    body: formData
  }).then(response => { response.json().then(res => {
    imageUrl.value = res.url
  })})
}

// 请求后端API保存报名信息
const saveEnrollInfo = async () => {
  const response = await fetch('/api1/user/save', {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      openid: "yangxingyao", // 必填，改成自己的openid，随意填写任意字符串不能与别人的重复，用户的唯一标识
      avater: "", 
      name: name.value,
      nickname: name.value,
      phone: phone.value,
      picture: imageUrl.value
    })
  })
  const res = await response.json()
  if(res.success){
    showSuccessToast("报名成功")
    setTimeout(() => {
      router.push({
        name: 'home'
      })
    }, 1000)
  }
  console.log('res', res)
}
</script>

<template>
  <div class="enroll">
    <h3>活动报名</h3>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="name"
          name="name"
          label="名称"
          placeholder="名称"
          :rules="[{ required: false, message: '请填写名称' }]"
        />
        <van-field
          v-model="phone"
          type="phone"
          name="phone"
          label="手机"
          placeholder="手机"
          :rules="[{ required: false, message: '手机' }]"
        />
        <van-field name="uploader" label="文件上传">
          <template #input>
            <van-uploader max-count="1" v-model="imageValue" :after-read="afterRead" />
          </template>
        </van-field>


      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

  </div>
</template>

<style>
@media (min-width: 1024px) {
  .enroll {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
.enroll h3{
  text-align: center;
  margin: 50px;
}
</style>
